package com.cqut.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cqut.model.RoleRigth;
import com.cqut.model.Role;
import com.cqut.service.IRoleService;
import com.cqut.dao.RoleMapper;
import com.cqut.dao.RoleMapperExtra;
import com.cqut.dao.RoleRigthMapper;
import com.cqut.dto.LimitShowDTO;
import com.cqut.dto.LoginInfoDTO;
import com.cqut.dto.RoleDTO;
import com.cqut.dto.RoleRigthDTO;
import com.cqut.util.SqlUtil;
import com.cqut.util.StringUtil;
import com.cqut.util.SystemConstants;

@Service
public class RoleService implements IRoleService {
    @Resource(name="roleMapper")
    private RoleMapper roleMapper;
   
    @Resource(name="roleMapperExtra")
    private RoleMapperExtra roleMapperExtra;
    
    @Override
    public boolean save(Role role) {
        return roleMapper.insert(role) > 0;
    }

    @Override
    public boolean update(Role role) {
        return roleMapper.updateByPrimaryKeySelective(role) >= 0;
    }

    @Override
    public boolean delete(String roleId) {
        return roleMapper.deleteByPrimaryKey(roleId) > 0;
    }

    @Override
    public boolean batchDelete(String[] primaryKeys) {
        return roleMapper.deleteByPrimaryKeys(primaryKeys) > 0;
    }

    @Override
    public Role findModel(String roleId) {
        return roleMapper.selectByPrimaryKey(roleId);
    }

    @Override
    public Role findModel(String roleId, String[] parameters) {
        return roleMapper.findModel(roleId, SqlUtil.formatParameters(parameters));
    }

    public Map<String, Object> findMap(String roleId) {
        String[][] parameters = {{"role_id", "roleId"}, {"role_name", "roleName"}, {"state", "state"}, {"remark", "remark"}};
        return this.findMap(roleId, parameters);
    }

    public Map<String, Object> findMap(String roleId, String[][] parameters) {
        return roleMapper.findMap(roleId, SqlUtil.formatParametersForAlias(parameters));
    }

    @Override
    public List<Role> loadModels() {
        return this.loadModels(null, null, null, null, -1, -1);
    }

    @Override
    public List<Role> loadModels(String condition, Object[] values, String order, String sort, int curPage, int limit) {
        return this.loadModels(null, condition, values, order, sort, curPage, limit);
    }

    @Override
    public List<Role> loadModels(String[] parameters, String condition, Object[] values, String order, String sort, int curPage, int limit) {
        return roleMapper.loadModels(SqlUtil.formatParameters(parameters), SqlUtil.fillCondition(condition, values), order, sort, SqlUtil.getOffset(curPage, limit), limit);
    }

    @Override
    public List<Map<String, Object>> loadMaps() {
        String[][] parameters = {{"role_id", "roleId"}, {"role_name", "roleName"}, {"state", "state"}, {"remark", "remark"}};
        return this.loadMaps(parameters, null, null, null, null, -1, -1);
    }

    @Override
    public List<Map<String, Object>> loadMaps(String condition, Object[] values, String order, String sort, int curPage, int limit) {
        String[][] parameters = {{"role_id", "roleId"}, {"role_name", "roleName"}, {"state", "state"}, {"remark", "remark"}};
        return this.loadMaps(parameters, condition, values, order, sort, curPage, limit);
    }

    @Override
    public List<Map<String, Object>> loadMaps(String[][] parameters, String condition, Object[] values, String order, String sort, int curPage, int limit) {
        return roleMapper.loadMaps(SqlUtil.formatParametersForAlias(parameters), SqlUtil.fillCondition(condition, values), order, sort, SqlUtil.getOffset(curPage, limit), limit);
    }

    @Override
    public long count() {
        return this.count(null, false);
    }

    @Override
    public long count(String condition, Object[] values) {
        return this.count(null, condition, values, false);
    }

    @Override
    public long count(String[] parameters, boolean isDistinct) {
        return this.count(parameters, null, null, isDistinct);
    }

    @Override
    public long count(String[] parameters, String condition, Object[] values, boolean isDistinct) {
        return roleMapper.count(SqlUtil.formatParameters(parameters), SqlUtil.fillCondition(condition, values), isDistinct);
    }
    
    /**
     * 根据条件获得roles列表
     * **/
    @Override
	public List<Map<String, Object>> findRolesWithLimit(String roleName,LimitShowDTO limitShowDTO) {
		return roleMapperExtra.findRolesByLimit(roleName,limitShowDTO.calculateStart(),limitShowDTO.calculateEnd());
	}
    
    /**
     * 根据条件获得count数
     * **/
    @Override
	public long findCountOfRoles(String roleName) {
		long count= roleMapperExtra.findCountByLimit(roleName);
		return count;
	} 

	@Override
	public boolean addOperator(String name, String password, String sex,
			String state, String type,String phone,String email,String college) {
		// TODO Auto-generated method stub
		String roleId = StringUtil.createTimestamp();
		String userId = roleId;
		
		/*if(roleMapperExtra.insertIntoRole(name,password,sex,state,type,roleId)<=0)
			return false;
		if(roleMapperExtra.insertIntoUser()<=0)*/
		return true;
	}

	
	/**
	 * 获得新的roleId
	 * **/
	public String getMaxRoleId(){
		Map<String, Object> maxRoleId = roleMapperExtra.findMaxCodeByRoleId();
		
		String temp = maxRoleId.values().toString();
		
		int max = Integer.parseInt(temp.substring(1,temp.length()-1));
		max++;
		String maxNum = Integer.toString(max);
		switch(maxNum.length()){
		case 1: return "000"+max;
		case 2: return "00"+max;	
		case 3: return "0"+max;
		}
		return "";
	}
		
	/**
	 * 添加新的角色以及角色权限
	 * **/
	public boolean addRoleAndRolePermission(RoleDTO roleDTO,RoleRigthDTO roleRigthDTO,int maxRoleRightId){	
		
 		String maxRoleId = getMaxRoleId();
		Role roleModel = roleDTO.toModel();

		roleDTO.setRoleId(maxRoleId);
		
		roleModel.setRoleId(roleDTO.getRoleId());
		roleModel.setRemark(roleDTO.getRemark());
		roleModel.setRoleName(roleDTO.getRoleName());
		roleModel.setState(roleDTO.getState());
		
		// 新增角色
		if(!save(roleModel))
			return false; 
				
		// 进行权限的分配
        addRoleAndRolePerm(maxRoleId,roleDTO.getRemark(),maxRoleRightId,roleRigthDTO.getMenuId());
		return true;
	}
	
	public boolean addRoleAndRolePerm(String roleId,String remark,int roleRightID, String[] moduleCodes) {	
		// 进行权限的分配
		batchInsertRolePerm(roleId, remark, roleRightID, moduleCodes);
		
		return true;  
	} 
	
	// 新增角色权限
	private int batchInsertRolePerm(String roleId,String remark,int roleRightID, String[] moduleCodes) {
		return roleMapperExtra.batchInsertPerm(createPermissionAssigns(roleId, remark, roleRightID, moduleCodes));
	}
	
	/**
	 * 通过角色id与模块id数组生成权限分配实体
	 * */
	private List<RoleRigth> createPermissionAssigns(String roleId,String remark,int roleRightID, String[] moduleCodes) {
 		List<RoleRigth> pas = new ArrayList<RoleRigth>();
		
		for(String moduleCode : moduleCodes) {
			
			RoleRigth pa = new RoleRigth();
			pa.setRoleRightId(getNewRoleRightId(roleRightID));
			pa.setRemark(remark);
			pa.setRoleId(roleId);
			pa.setMenuId(moduleCode);
			pas.add(pa);
			roleRightID++;
		}
		
		return pas;
	}
	
	/**
	 * 传入roleId生成新的roleId
	 * **/
	public String getNewRoleRightId(int max){
		
		String maxNum = Integer.toString(max);
		switch(maxNum.length()){
		case 1: return "0000"+max;
		case 2: return "000"+max;	
		case 3: return "00"+max;
		case 4: return "0"+max;
		}
		return "";
	}
	
	/**
	 * 删除角色以及角色下已分配的权限
	 */
	@Transactional
	public boolean deleteRoleByIds(String[] roleIds) {
		int deleteRoles = roleMapper.deleteByPrimaryKeys(roleIds);//删除角色表里的角色
		if(deleteRoles > 0)
			return true;
		return false;
	}

	/**
	 * 修改角色以及角色权限
	 * **/
	public boolean upadateRoleAndRolePermission(RoleDTO roleDTO, RoleRigthDTO roleRigthDTO, int maxRoleRightId){	
		
		Role roleModel = roleDTO.toModel();

		roleModel.setRoleId(roleDTO.getRoleId());
		roleModel.setRemark(roleDTO.getRemark());
		roleModel.setRoleName(roleDTO.getRoleName());
		roleModel.setState(roleDTO.getState());
		
		// 新增角色
		if(!(roleMapper.updateByPrimaryKeySelective(roleModel)>=0))
			return false; 
				
		//进行权限的分配
        addRoleAndRolePerm(roleDTO.getRoleId(),roleDTO.getRemark(),maxRoleRightId,roleRigthDTO.getMenuId());
		return true;
	}


}
